﻿using System.Threading.Tasks;
using MongoDB.Driver;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.Synchronization.Validation.Handlers.Common;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Synchronization.Validation.Handlers.Comprehensive
{
    public class ComprehensiveCorporateDataLoader
    {
        private readonly IMongoCollection<CompanyProfileResearchState> mongoCollection;
        private readonly ComprehensiveCompanies comprehensiveCompanies;
        private readonly WhiteListCompanies whiteListCompanies;

        public ComprehensiveCorporateDataLoader(IMongoCollection<CompanyProfileResearchState> mongoCollection, ComprehensiveCompanies comprehensiveCompanies, WhiteListCompanies whiteListCompanies)
        {
            this.mongoCollection = mongoCollection;
            this.comprehensiveCompanies = comprehensiveCompanies;
            this.whiteListCompanies = whiteListCompanies;
        }

        public async Task LoadAsync()
        {
            var values = await mongoCollection.Find(Builders<CompanyProfileResearchState>.Filter.Where(x => x.ComprehensiveEsgResearchState.ResearchState == ResearchState.ResearchAvailable))
                .Project(x => new
                {
                    Id = x.Id,
                    CapitalIqId = x.CapitalIqId
                }).ToListAsync().ConfigureAwait(false);

            foreach (var value in values)
            {
                if (!comprehensiveCompanies.Contains(value.Id) &&
                    !whiteListCompanies.Exists(x => x.CapitalIqId == value.CapitalIqId && x.ResearchProduct == BusinessResearchProduct.Comprehensive))
                    comprehensiveCompanies.Add(value.Id);                
            }
        }
    }
}
